home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / tex / egrep.zip / REGX.ZIP / REGEXP.C < prev    next >
Text File  |  1988-03-31  |  29KB  |  1,217 lines

  1. /*
  2.  * regcomp and regexec -- regsub and regerror are elsewhere
  3.  *
  4.  *    Copyright (c) 1986 by University of Toronto.
  5.  *    Written by Henry Spencer.  Not derived from licensed software.
  6.  *
  7.  *    Permission is granted to anyone to use this software for any
  8.  *    purpose on any computer system, and to redistribute it freely,
  9.  *    subject to the following restrictions:
  10.  *
  11.  *    1. The author is not responsible for the consequences of use of
  12.  *        this software, no matter how awful, even if they arise
  13.  *        from defects in it.
  14.  *
  15.  *    2. The origin of this software must not be misrepresented, either
  16.  *        by explicit claim or by omission.
  17.  *
  18.  *    3. Altered versions must be plainly marked as such, and must not
  19.  *        be misrepresented as being the original software.
  20.  *
  21.  * Beware that some of this code is subtly aware of the way operator
  22.  * precedence is structured in regular expressions.  Serious changes in
  23.  * regular-expression syntax might require a total rethink.
  24.  */
  25. #include <stdio.h>
  26. #include <regexp.h>
  27. #include <string.h>
  28. #include "regmagic.h"
  29.  
  30. /*
  31.  * The "internal use only" fields in regexp.h are present to pass info from
  32.  * compile to execute that permits the execute phase to run lots faster on
  33.  * simple cases.  They are:
  34.  *
  35.  * regstart    char that must begin a match; '\0' if none obvious
  36.  * reganch    is the match anchored (at beginning-of-line only)?
  37.  * regmust    string (pointer into program) that match must include, or NULL
  38.  * regmlen    length of regmust string
  39.  *
  40.  * Regstart and reganch permit very fast decisions on suitable starting points
  41.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  42.  * of lines that cannot possibly match.  The regmust tests are costly enough
  43.  * that regcomp() supplies a regmust only if the r.e. contains something
  44.  * potentially expensive (at present, the only such thing detected is * or +
  45.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  46.  * supplied because the test in regexec() needs it and regcomp() is computing
  47.  * it anyway.
  48.  */
  49.  
  50. /*
  51.  * Structure for regexp "program".  This is essentially a linear encoding
  52.  * of a nondeterministic finite-state machine (aka syntax charts or
  53.  * "railroad normal form" in parsing technology).  Each node is an opcode
  54.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  55.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  56.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  57.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  58.  * opposed to a collection of them) is never concatenated with anything
  59.  * because of operator precedence.)  The operand of some types of node is
  60.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  61.  * particular, the operand of a BRANCH node is the first node of the branch.
  62.  * (NB this is *not* a tree structure:  the tail of the branch connects
  63.  * to the thing following the set of BRANCHes.)  The opcodes are:
  64.  */
  65.  
  66. /* definition    number    opnd?    meaning */
  67. #define    END    0    /* no    End of program. */
  68. #define    BOL    1    /* no    Match "" at beginning of line. */
  69. #define    EOL    2    /* no    Match "" at end of line. */
  70. #define    ANY    3    /* no    Match any one character. */
  71. #define    ANYOF    4    /* str    Match any character in this string. */
  72. #define    ANYBUT    5    /* str    Match any character not in this string. */
  73. #define    BRANCH    6    /* node    Match this alternative, or the next... */
  74. #define    BACK    7    /* no    Match "", "next" ptr points backward. */
  75. #define    EXACTLY    8    /* str    Match this string. */
  76. #define    NOTHING    9    /* no    Match empty string. */
  77. #define    STAR    10    /* node    Match this (simple) thing 0 or more times. */
  78. #define    PLUS    11    /* node    Match this (simple) thing 1 or more times. */
  79. #define    OPEN    20    /* no    Mark this point in input as start of #n. */
  80.             /*    OPEN+1 is number 1, etc. */
  81. #define    CLOSE    30    /* no    Analogous to OPEN. */
  82.  
  83. /*
  84.  * Opcode notes:
  85.  *
  86.  * BRANCH    The set of branches constituting a single choice are hooked
  87.  *        together with their "next" pointers, since precedence prevents
  88.  *        anything being concatenated to any individual branch.  The
  89.  *        "next" pointer of the last BRANCH in a choice points to the
  90.  *        thing following the whole choice.  This is also where the
  91.  *        final "next" pointer of each individual branch points; each
  92.  *        branch starts with the operand node of a BRANCH node.
  93.  *
  94.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  95.  *        exists to make loop structures possible.
  96.  *
  97.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  98.  *        BRANCH structures using BACK.  Simple cases (one character
  99.  *        per match) are implemented with STAR and PLUS for speed
  100.  *        and to minimize recursive plunges.
  101.  *
  102.  * OPEN,CLOSE    ...are numbered at compile time.
  103.  */
  104.  
  105. /*
  106.  * A node is one char of opcode followed by two chars of "next" pointer.
  107.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  108.  * value is a positive offset from the opcode of the node containing it.
  109.  * An operand, if any, simply follows the node.  (Note that much of the
  110.  * code generation knows about this implicit relationship.)
  111.  *
  112.  * Using two bytes for the "next" pointer is vast overkill for most things,
  113.  * but allows patterns to get big without disasters.
  114.  */
  115. #define    OP(p)    (*(p))
  116. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + *((p)+2)&0377)
  117. #define    OPERAND(p)    ((p) + 3)
  118.  
  119. /*
  120.  * See regmagic.h for one further detail of program structure.
  121.  */
  122.  
  123.  
  124. /*
  125.  * Utility definitions.
  126.  */
  127. #ifndef CHARBITS
  128. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  129. #else
  130. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  131. #endif
  132.  
  133. #define    FAIL(m)    { regerror(m); return(NULL); }
  134. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  135. #define    META    "^$.[()|?+*\\"
  136.  
  137. /*
  138.  * Flags to be passed up and down.
  139.  */
  140. #define    HASWIDTH    01    /* Known never to match null string. */
  141. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  142. #define    SPSTART        04    /* Starts with * or +. */
  143. #define    WORST        0    /* Worst case. */
  144.  
  145. /*
  146.  * Global work variables for regcomp().
  147.  */
  148. static char *regparse;        /* Input-scan pointer. */
  149. static int regnpar;        /* () count. */
  150. static char regdummy;
  151. static char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  152. static long regsize;        /* Code size. */
  153.  
  154. /*
  155.  * Forward declarations for regcomp()'s friends.
  156.  */
  157. #ifndef STATIC
  158. #define    STATIC    static
  159. #endif
  160. STATIC char *reg();
  161. STATIC char *regbranch();
  162. STATIC char *regpiece();
  163. STATIC char *regatom();
  164. STATIC char *regnode();
  165. STATIC char *regnext();
  166. STATIC void regc();
  167. STATIC void reginsert();
  168. STATIC void regtail();
  169. STATIC void regoptail();
  170. #ifdef STRCSPN
  171. STATIC int strcspn();
  172. #endif
  173.  
  174. /*
  175.  - regcomp - compile a regular expression into internal code
  176.  *
  177.  * We can't allocate space until we know how big the compiled form will be,
  178.  * but we can't compile it (and thus know how big it is) until we've got a
  179.  * place to put the code.  So we cheat:  we compile it twice, once with code
  180.  * generation turned off and size counting turned on, and once "for real".
  181.  * This also means that we don't allocate space until we are sure that the
  182.  * thing really will compile successfully, and we never have to move the
  183.  * code and thus invalidate pointers into it.  (Note that it has to be in
  184.  * one piece because free() must be able to free it all.)
  185.  *
  186.  * Beware that the optimization-preparation code in here knows about some
  187.  * of the structure of the compiled regexp.
  188.  */
  189. regexp *
  190. regcomp(exp)
  191. char *exp;
  192. {
  193.     register regexp *r;
  194.     register char *scan;
  195.     register char *longest;
  196.     register int len;
  197.     int flags;
  198.     extern char *malloc();
  199.  
  200.     if (exp == NULL)
  201.         FAIL("NULL argument");
  202.  
  203.     /* First pass: determine size, legality. */
  204.     regparse = exp;
  205.     regnpar = 1;
  206.     regsize = 0L;
  207.     regcode = ®dummy;
  208.     regc(MAGIC);
  209.     if (reg(0, &flags) == NULL)
  210.         return(NULL);
  211.  
  212.     /* Small enough for pointer-storage convention? */
  213.     if (regsize >= 32767L)        /* Probably could be 65535L. */
  214.         FAIL("regexp too big");
  215.  
  216.     /* Allocate space. */
  217.     r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
  218.     if (r == NULL)
  219.         FAIL("out of space");
  220.  
  221.     /* Second